package tech.veedo.munchkin.services.backend.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tech.veedo.munchkin.beans.basic.User;
import tech.veedo.munchkin.beans.backend.Workflow;
import tech.veedo.munchkin.mappers.backend.WorkflowMapper;
import tech.veedo.munchkin.services.backend.WorkflowService;

import java.util.Objects;

@Slf4j
@Service
public class WorkflowServiceImpl extends ServiceImpl<WorkflowMapper, Workflow> implements WorkflowService {

    @Override
    @Transactional
    public boolean saveWorkflow(Workflow workflow, User user) {
        workflow.setVersion(1L);
        workflow.setCreatePsn(user.getPsnName());
        return save(workflow);
    }

    @Override
    @Transactional
    public boolean updateWorkflow(Workflow workflow, User user) {
        Workflow fromDB = getById(workflow.getId());
        if (ObjectUtils.isEmpty(fromDB)) {
            throw new NullPointerException("顶层工作流(id:"+workflow.getId()+")在数据库中未找到，请刷新");
        }
        if (!Objects.equals(workflow.getVersion(), fromDB.getVersion())) {
            throw new IllegalStateException("当前顶层工作流版本与操作时不符，请刷新");
        }
        fromDB.setName(workflow.getName());
        fromDB.setUpdatePsn(user.getPsnName());
        return updateById(fromDB);
    }

    @Override
    @Transactional
    public boolean deleteWorkflow(Long id, User user) {
        Workflow fromDB = getById(id);
        if (ObjectUtils.isEmpty(fromDB)) {
            throw new NullPointerException("顶层工作流(id:"+id+")在数据库中未找到，请刷新");
        }
        // process the deleting auditForms...
        // code here...

        return removeById(id);
    }

}
